package com.sk.bilibili.utils;

import com.sk.bilibili.dto.PushInfo;
import com.sk.bilibili.property.LiveProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 邵康
 * @date 2021/11/26 10:12
 */
@Component
public class LiveUtils {

    private static final String URL_PATH="%s/%s/%s.flv";
    private static final String SERVER_PATH="%s/%s/";
    private static final String SECRET_PATH="%s?txSecret=%s&txTime=%s";
    private static final Pattern URL_PATTERN=Pattern.compile(".*/(.*)\\.flv");

    @Autowired
    private LiveProperty liveProperty;

    public String generateUrl() {
        String name = NameCreator.getName();
        return String.format(URL_PATH,liveProperty.getPushServer(),liveProperty.getAppName(),name);
    }

    public PushInfo generatePushInfo(String url) {
        Matcher matcher = URL_PATTERN.matcher(url);
        if(matcher.find()){
            String name=matcher.group(1);
            long time=System.currentTimeMillis()/1000+liveProperty.getExpiration();
            String hexTime=Long.toHexString(time);
            byte[] bytes = (liveProperty.getKey() + name + hexTime).getBytes();
            String txSecret = DigestUtils.md5DigestAsHex(bytes);
            PushInfo pushInfo=new PushInfo();
            pushInfo.setServer(String.format(SERVER_PATH,liveProperty.getPullServer(),liveProperty.getAppName()));
            pushInfo.setKey(String.format(SECRET_PATH,name,txSecret,hexTime));
            return pushInfo;
        }
        return null;
    }

}
